package com.example.MyRESTAssured.restAsurred;

import io.restassured.RestAssured;
import io.restassured.mapper.TypeRef;
import io.restassured.parsing.Parser;
import org.junit.Test;

import java.util.List;
import java.util.Map;

import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.when;
import static io.restassured.path.json.JsonPath.from;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;

public class JSONTest {

    @Test
    public void TestvalidateJSONGroovyGetRequest(){

        RestAssured.registerParser("text/plain", Parser.JSON);

        when().
                get("/store")
                .then()
                .body("store.book.findAll { it.price < 10 }.title", hasItems("Sayings of the Century", "Moby Dick"))
                .body("store.book.author.collect { it.length() }.sum()", greaterThan(50))
                .body("store.book.author*.length().sum()", greaterThan(50));

        String response = get("/store").asString();
        List<String> bookTitles = from(response).getList("store.book.findAll { it.price < 10 }.title");
        System.out.println(bookTitles);

        int sumOfAllAuthorLengths = from(response).getInt("store.book.author*.length().sum()");
        assertThat(sumOfAllAuthorLengths, is(53));

        System.out.println("使用groovy表达式查询数据成功！");

    }


    @Test
    public void TestvalidateDeserializationGetRequest(){
        RestAssured.registerParser("text/plain", Parser.JSON);

        List<Map<String, Object>> products = get("/products").as( new TypeRef<List<Map<String, Object>>>() {} );

        assertThat(products, hasSize(2));
        assertThat(products.get(0).get("id"), equalTo(2));
        assertThat(products.get(0).get("name"), equalTo("An ice sculpture"));
        assertThat(products.get(0).get("price"), equalTo(12.5));
        assertThat(products.get(1).get("id"), equalTo(3));
        assertThat(products.get(1).get("name"), equalTo("A blue mouse"));
        assertThat(products.get(1).get("price"), equalTo(25.5));

        System.out.println(products);
        System.out.println("反序列化范型验证成功！");

    }


}
